<?php

namespace App\Listeners;

use App\Events\WechatTemplateMessage;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Queue\InteractsWithQueue;
use EasyWeChat\Factory;

class SendWechatTemplateMessage
{
    /**
     * Create the event listener.
     *
     * @return void
     */
    protected $app;
    public function __construct()
    {
        $config = [
            'app_id' => env('WECHAT_OFFICIAL_ACCOUNT_APPID', ''),
            'secret' => env('WECHAT_OFFICIAL_ACCOUNT_SECRET', ''),
            // 指定 API 调用返回结果的类型：array(default)/collection/object/raw/自定义类名
            'response_type' => 'array'
        ];

        $this->app = Factory::officialAccount($config);
    }

    /**
     * Handle the event.
     *
     * @param  WechatTemplateMessage  $event
     * @return void
     */
    public function handle(WechatTemplateMessage $event)
    {
        // 发送模板消息
        $msgData = $event->msgData;
        foreach($msgData as $data) {
            $this->app->template_message->send($data);
        }
        
        // $this->app->template_message->send([
        //     'touser' => 'ok2z06CL1qBjcvfHqMID3s2z1mZ4',
        //     'template_id' => 'wRzO6tdaZVIzb-qkAmvjtchCH1D306BSzlBFHZDgH5I',
        //     'url' => 'https://www.dtx-tech.com',
        //     'data' => [
        //         'first' => '你好，有患者发来新的消息',
        //         'keyword1' => '肖',
        //         'keyword2' => nl2br(htmlspecialchars($data->content)),
        //         'keyword3' => date('Y-m-d H:i:s'),
        //         'remark' => '',
        //     ]
        // ]);
    }
}
